import { useCallback, useReducer } from "react"
import {KeepAliveReducer} from './keepAliveReducer'
import * as actionTypes from './types'
import { KeepAliveContext } from "./keepAliveContext"

function KeepAlive(props) {
    console.log('KeepAlive props=>', props);
    /**
     * {
     *   home: {
     *      keepAliveId: 'home',
     *      reactElement: reactElement,
     *      nodes: nodes,
     *      status: create | created
     *   },
     *   user: {
     *      keepAliveId: 'user',
     *      reactElement: reactElement,
     *      nodes: nodes,
     *      status: create | created
     *   }
     * }
     */
    const [keepAliveStates, dispatch] = useReducer(KeepAliveReducer, {})
    
    const setKeepAliveState = useCallback(({ reactElement, keepAliveId }) => {
        if(!keepAliveStates[keepAliveId]) {
            dispatch({
                type: actionTypes.CREATING,
                payload: {
                    keepAliveId,
                    reactElement
                }
            })
        }
    }, [keepAliveStates])

    return (
        <KeepAliveContext.Provider value={{
            keepAliveStates,
            setKeepAliveState,
            dispatch
        }}>
        { props.children }
        {
            Object.values(keepAliveStates).map(({ keepAliveId, reactElement }) => (
                <div key={ keepAliveId } ref={(node) => {
                    console.log(reactElement);
                    if(node && !keepAliveStates[keepAliveId].nodes) {
                    console.log(node.childNodes);

                        dispatch({
                            type: actionTypes.CREATED,
                            payload: {
                                keepAliveId,
                                nodes: [...node.childNodes]
                            }
                        })
                    }
                }}>{ reactElement }</div>
            ))
        }
        </KeepAliveContext.Provider>
    )
}

export default KeepAlive

